/*
 * @Description: 临时变量
 * @Author: HuiSir<273250950@qq.com>
 * @Date: 2021-09-15 11:25:57
 * @LastEditTime: 2025-08-14 11:54:21
 */
import { defineStore } from "pinia";
import { reactive, toRefs } from "vue";
import {
  RouteLocationNormalizedGeneric,
  RouteMeta,
  useRoute,
  useRouter,
} from "vue-router";

/* eslint-disable */

/**
 * state数据类型接口
 */
interface LayoutState extends Recordable {
  sidebarCollapse?: boolean;
  sidebarHide?: boolean;
  visibleAreaWidth?: number;
  visibleAreaHeight?: number;
  historyRoutes: {
    name: string;
    path: string;
    fullPath: string;
    meta: RouteMeta;
    params: Recordable;
    query: Recordable;
  }[];
}

export default defineStore("layout", () => {
  const _route = useRoute();
  const _router = useRouter();

  const state: LayoutState = reactive({
    /**
     * 侧边栏收起
     */
    sidebarCollapse: false,
    /**
     * 侧边栏隐藏
     */
    sidebarHide: false,
    /**
     * 屏幕可视区宽度
     */
    visibleAreaWidth: window.innerWidth,
    /**
     * 屏幕可视区高度
     */
    visibleAreaHeight: window.innerHeight,
    /**
     * 历史路由
     */
    historyRoutes: [],
  });

  // setStates 由于pinia的$patch方法可以取代此自定义方法，所以无需再定义

  /**
   * 侧边栏状态更改
   */
  const changeSidebarCollapse = () => {
    state.sidebarCollapse = !state.sidebarCollapse;
  };
  /**
   * 添加历史路由
   */
  const addHistoryRoute = (route: RouteLocationNormalizedGeneric) => {
    // 这里要判断query是否一致，不同query也同样新增tab,所以这里使用`fullPath`做判断
    if (
      !state.historyRoutes.some((item) => item.fullPath === route.fullPath) &&
      !route.meta.notInTabbar &&
      route.name
    ) {
      const { name, path, meta, params, query, fullPath } = route;
      state.historyRoutes.push({
        name: name as string,
        meta: meta as RouteMeta,
        path,
        fullPath,
        params,
        query,
      });
    }
  };
  /**
   * 删除历史路由
   */
  const delHistoryRoute = (route: any) => {
    const INDEX = state.historyRoutes.findIndex(
      (item) => item.fullPath === route.fullPath
    );
    state.historyRoutes.splice(INDEX, 1);
  };
  /**
   * 删除当前路由并回退路由
   */
  const goBack = () => {
    const INDEX = state.historyRoutes.findIndex(
      (item) => item.fullPath === _route.fullPath
    );
    state.historyRoutes.splice(INDEX, 1);
    _router.back();
  };
  /**
   * 清除历史路由
   */
  const clearHistoryRoute = () => {
    state.historyRoutes = [];
  };
  /**
   * 重设历史路由标题（tabbar标题）
   * @param fullPath 要设置的历史路由fullPath
   * @param title 新设的标题
   */
  const setHistoryRouteTitle = (fullPath: string, title: string) => {
    const index = state.historyRoutes.findIndex(
      (item) => item.fullPath === fullPath
    );
    state.historyRoutes[index].meta.title = title;
  };

  return {
    ...toRefs(state),
    changeSidebarCollapse,
    addHistoryRoute,
    delHistoryRoute,
    clearHistoryRoute,
    setHistoryRouteTitle,
    goBack,
  };
});
